const express=require('express');
const userRouter=express.Router();
const mysql=require('mysql')
const db=require('./../db/config')
module.exports=userRouter;
const userLogin=function(a,b){
    let idcd,password;
    if(a.method==='GET'){
     idcd=a.query.idcd;
     password=a.query.password
    }else if(a.method==='POST'){
        idcd=a.body.idcd;
        password=a.body.password;
    }
    if(idcd && password){
        let q='select * from yhm where username=? and password=?;';
        let w=[idcd,password];
        let e=(err,data)=>{
            if (!err && data.length === 1) {
                // console.log("登录系统操作成功")
                b.json({
                  code: 0,
                  msg: '登录系统操作成功',
                  data
                })
              } else {
                // console.log("登录系统操作失败")
                b.json({
                  code: 40001,
                  msg: '登录系统操作失败',
                  data
                })
              }  
        }
        let conn=mysql.createConnection({
            host:"127.0.0.1",
            port:3306,
            user:"root",
            password:'123456',
            database:'dom296',
            multipleStatements:true,
            timezone:'08:00'
        });
        
        conn.connect();
        conn.query(q,w,e);
        conn.end();
    } else{
        b.json({
            code:40001,
            msg:'用户名或密码是必须的'
        })
    }
    
}

userRouter.route("/user/login")
  .post(userLogin)
  .get(userLogin);

//注册接口
userRouter.route('/user/register')
.post(function(req,res){
  let {idcd,password}=req.body; 
  let sql='insert into yhm (id,username,password) values(null,?,?);';
  let params=[idcd,password];
  let cb=(err,data)=>{
    console.log(err,data);
if(!err){
  res.json({
    code:0,
    msg:'注册成功'
  })
}else{
  res.json({
    code:40001,
    msg:'注册失败'
  })
}
  }
  db.connect(sql,params,cb);
})